// @APIVersion 1.0.0
// @Title 脚本管理系统API
// @Description howie developer
// @Contact hwholiday@163.com
package routers

import (
	"github.com/astaxie/beego"
	"howie_api/controllers"
	"github.com/astaxie/beego/context"
	"howie_api/utils"
	"strings"
	"github.com/astaxie/beego/plugins/cors"
)

func init() {
	ns :=
		beego.NewNamespace("/v1",
			beego.NSNamespace("/user",
				beego.NSInclude(
					&controllers.AuthControllers{},
				),
			),
		)
	beego.AddNamespace(ns)

	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type", "Token"},
		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
		AllowCredentials: true,
	}))

	beego.InsertFilter("*", beego.BeforeRouter, FilterUser, true) // 验证登陆
}

var FilterUser = func(ctx *context.Context) {
	if strings.Contains(ctx.Request.RequestURI, "/login")||
		strings.Contains(ctx.Request.RequestURI, "/register")||
			strings.Contains(ctx.Request.RequestURI, "/administer_list") {
		return
	}
	token := ctx.Input.Header("Token")
	var err error
	if _, err = utils.GetUidByToken(token); err != nil {
		ctx.Output.SetStatus(controllers.CODE_TOKEN_ERR)
		ctx.Output.JSON(err.Error(), false, false)
		return
	}
	return
}
